package com.cxmx.escort.common.exception;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.*;

/**
 * @author chenkuidou
 */
@ControllerAdvice
@ResponseBody
public class ExceptionAdvice {
    @Autowired
    private HttpServletRequest request;

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Object MethodArgumentNotValidHandler(MethodArgumentNotValidException exception) { //按需重新封装需要返回的错误信息
        Map map = new HashMap();
        List<String> msgList = new ArrayList<>();
        //解析原错误信息，封装后返回，此处返回非法的字段名称，错误信息
        for (FieldError error : exception.getBindingResult().getFieldErrors()) {
            msgList.add(error.getDefaultMessage());
        }
        map.put("code", "0");
        map.put("msg", "参数错误");
        map.put("data", msgList);
        return map;
    }

    /**
     * 拦截捕捉自定义异常 ConstraintViolationException.class
     *
     * @param
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = ConstraintViolationException.class)
    public Map ConstraintViolationExceptionHandler(ConstraintViolationException ex) {
        Map map = new HashMap();
        Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
        Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
        List<String> msgList = new ArrayList<>();
        while (iterator.hasNext()) {
            ConstraintViolation<?> cvl = iterator.next();
            msgList.add(cvl.getMessageTemplate());
        }
        map.put("code", "0");
        map.put("msg", "参数错误");
        map.put("data", msgList);
        return map;
    }

    @ExceptionHandler(MyException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Map<String, Object> handlerMyException(MyException ex) {
        Map<String, Object> result = new HashMap<>();
        result.put("msg", ex.getMessage());
        result.put("code", "0");
        result.put("data", "");
        return result;
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Map<String, Object> handlerException(Exception ex) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", "0");
        result.put("msg", "系统错误");
        result.put("data", ex.getMessage());
        return result;
    }

}
